package com.toy.core.security.concurrent;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.toy.core.security.AuthenticatedType;
import com.toy.core.security.Authentication;
import com.toy.core.security.UsernamePasswordAuthentication;

public class SessionRegistryInMemory implements SessionRegistry {
	
	private Map<String , SessionToken> tokens = new HashMap<String, SessionToken>();
	
	public SessionToken getByToken(String ticket) {
		return tokens.get(ticket);
	}

	public SessionToken registerSession(Authentication authentication) {
		UsernamePasswordAuthentication auth = (UsernamePasswordAuthentication)authentication;
		SessionToken token = new SessionToken();
		String ticket = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
		token.setToken(ticket);
		token.setLoginSucceedTime(new Date());
		token.setRemoteAddr((String)auth.getAttribute(Authentication.ATTR_REMOTEADDR));
		token.setSessionId((String)auth.getAttribute(Authentication.ATTR_SESSIONID));
		token.setUserName((String)auth.getPrincipal());
		token.setAuthenticatedType(((AuthenticatedType)auth.getAttribute(Authentication.ATTR_AUTHENTICATED_TYPE)).toString());
		tokens.put(ticket, token);
		return token;
	}

	public void removeByToken(String ticket) {
		tokens.remove(ticket);
	}

	public void updateSessionToken(SessionToken st) {

	}

}
